<template>
  <div class="mb-3">
    <button type="button" class="btn btn-primary px-3" @click="openModal('add')">
      <i class="far fa-edit me-2"></i>新增
    </button>
  </div>
  <table class="table table-bordered table-hover table-striped">
    <thead>
      <tr>
        <th scope="col"></th>
        <th scope="col">用户名</th>
        <th scope="col">角色</th>
        <th scope="col">性别</th>
        <th scope="col">头像</th>
        <th scope="col">地址</th>
        <th scope="col">操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="item in lists" :key="item.id">
        <th scope="row">1</th>
        <td>{{ item.username }}</td>
        <td>{{ item.roles?.map(o => o.name).join(',') }}</td>
        <td>{{ item.profile?.gender === 1 ? '男' : '女' }}</td>
        <td>{{ item.profile?.photo }}</td>
        <td>{{ item.profile?.address }}</td>
        <td>
          <button type="button" class="btn btn-secondary btn-sm px-3" @click="openModal('edit', item)">
            <i class="far fa-edit me-2"></i>编辑
          </button>
          <button type="button" class="btn btn-danger btn-sm px-3 ms-2" @click="openModal('delete', item)">
            <i class="far fa-trash-alt me-2"></i> 删除
          </button>
        </td>
      </tr>
    </tbody>
  </table>
  <nav aria-label="Page navigation example">
    <ul class="pagination">
      <li class="page-item"><a class="page-link" href="#">Previous</a></li>
      <li class="page-item"><a class="page-link" href="#">1</a></li>
      <li class="page-item"><a class="page-link" href="#">2</a></li>
      <li class="page-item"><a class="page-link" href="#">3</a></li>
      <li class="page-item"><a class="page-link" href="#">Next</a></li>
    </ul>
  </nav>

  <!-- Update Modal -->
  <!-- <div class="modal fade" ref="editRef" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">{{ msg }}</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <Form :schema="formSchema"></Form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" @click="editSubmit()">保存</button>
        </div>
      </div>
    </div>
  </div> -->

  <!-- Delete Modal -->
  <!-- <div class="modal fade" ref="deleteRef" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">删除</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          确定删除该用户吗？
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" @click="deleteSubmit()">确定</button>
        </div>
      </div>
    </div>
  </div> -->
  <EditAddModal v-model:show="showEditAddModal" :msg="msg" :schema="formSchema" @submit="editSubmit"></EditAddModal>
  <DeleteModal v-model:show="showDeleteModal" @delete="deleteSubmit" :msg="'确定删除该用户吗？'"></DeleteModal>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref } from 'vue'
import axios from '@/utils/axios';
import { getAllUsers } from '@/api/user';
// import * as bootstrap from 'bootstrap';

import DeleteModal from '@/components/modal/DeleteModal.vue';
import EditAddModal from '@/components/modal/EditAddModal.vue';

import { FormItem } from '@/components/Form.vue';

interface Profile {
  gender: number;
  address: string;
  photo: string;
}
interface RoleItem {
  id: number;
  name: string;
}
interface UserItem {
  [key: string]: any;
  id: number;
  username: string;
  password?: string;
  profile: Profile;
  roles: RoleItem[];
}

export default defineComponent({
  components: {
    DeleteModal,
    EditAddModal
  },
  setup() {
    const lists = ref([] as UserItem[])
    const tmpItem = ref({} as UserItem)

    const formSchema = [
      {
        field: '用户名',
        type: 'input',
        prop: 'username',
        value: '',
        attr: {
          placeholder: '请输入用户名',
        }
      },
      {
        field: '密码',
        type: 'input',
        prop: 'password',
        value: '',
        attr: {
          placeholder: '请输入密码',
        }
      },
      {
        field: '角色',
        type: 'checkbox',
        prop: 'roles',
        value: [],
        children: [
          {
            value: 1,
            field: '普通用户'
          },
          {
            value: 2,
            field: '管理员'
          },
          {
            value: 3,
            field: '测试用户'
          },
        ]
      },
      {
        field: '性别',
        type: 'radio',
        prop: 'gender',
        value: 0,
        children: [
          {
            value: 1,
            field: '男'
          },
          {
            value: 2,
            field: '女'
          },
        ]
      },
      {
        field: '头像',
        type: 'input',
        prop: 'photo',
        value: '',
        attr: {
          placeholder: '请输入头像链接',
        }
      },
      {
        field: '地址',
        type: 'input',
        prop: 'address',
        value: '',
        attr: {
          placeholder: '请输入地址',
        }
      },
    ] as FormItem[]

    const showEditAddModal = ref(false)
    const showDeleteModal = ref(false)

    const formValue = reactive({
      id: 0,
      username: '',
      password: '',
      profile: {
        gender: 0,
        address: '',
        photo: ''
      } as Profile,
      roles: [] as RoleItem[]
    } as UserItem)

    // dom 绑定
    // const deleteRef = ref();
    // const editRef = ref();

    // 模态框的控制 handler
    // const deleteModal = ref();
    // const editAndAddModal = ref();
    const msg = ref('新增' as ('编辑' | '新增'));
    // let localType: string = ''

    // 获取用户列表
    const getUserList = async () => {
      const res = (await getAllUsers()) as unknown as UserItem[]
      if (res && res.length > 0) {
        lists.value = res
      }
    }

    onMounted(async() => {
      // 初始化用户列表
      await getUserList()

      // 模态框创建
      // deleteModal.value = new bootstrap.Modal(deleteRef.value, {
      //   backdrop: true
      // })
      // editAndAddModal.value = new bootstrap.Modal(editRef.value, {
      //   backdrop: true
      // })
    })

    const openModal = (type: string, item?: UserItem) => {
      // localType = type
      tmpItem.value = item || {} as UserItem;
      if (type === 'delete') {
        // deleteModal.value.show();
        showDeleteModal.value = true;
      } else if (type === 'edit') {
        msg.value = '编辑';
        // Object.assign(formValue, tmpItem.value)
        // formValue.roles = tmpItem.value.roles.map(o => o.id)
        // console.log("🚀 ~ openModal ~ formValue:", formValue)
        // editAndAddModal.value.show();
        console.log("🚀 ~ openModal ~ formSchema:", formSchema)
        console.log("🚀 ~ openModal ~ tmpItem:", tmpItem)
        for (const k in formSchema) {
          if (Object.prototype.hasOwnProperty.call(formSchema, k)) {
            const el = formSchema[k];
            el.value = tmpItem.value[el.prop]
          }
        }
        showEditAddModal.value = true;
      } else if (type === 'add') {
        msg.value = '新增';
        // editAndAddModal.value.show();
        showEditAddModal.value = true;
      }
    }


    const editSubmit = async (val: any) => {
      console.log(val);
      // // 判断用户是新增还是编辑
      // if (localType === 'add') {
      //   // 发送对应的数据到接口
      //   const res = await axios.post('/user', val)
      //   // 清空 form 表单
      //   // console.log("🚀 ~ editSubmit ~ res:", res)
      //   Object.assign(val, {
      //     id: 0,
      //     username: '',
      //     password: '',
      //     profile: {
      //       gender: 0,
      //       address: '',
      //       photo: ''
      //     } as Profile,
      //     roles: [] as RoleItem[]
      //   })
      // } else if (localType === 'edit'){
      //   const res = await axios.patch(`/user/${formValue.id}`, formValue, {
      //     headers: {
      //       'Authorization': formValue.id
      //     }
      //   })
      //   console.log("🚀 ~ editSubmit ~ res:", res)
      // }
      // // 关闭模态框
      // // editAndAddModal.value.hide();
      // showEditAddModal.value = false;
      // await getUserList();
    }

    const deleteSubmit = async () => {
      const id = tmpItem.value.id

      const res = await axios.delete(`/user/${id}`) as UserItem

      // console.log("🚀 ~ deleteSubmit ~ res:", res)
      if (res.username === tmpItem.value.username){
        // 关闭模态框
        // deleteModal.value.hide();
        showDeleteModal.value = false;
        await getUserList();
      }
    }

    return {
      lists,
      // deleteRef,
      // editRef,
      openModal,
      msg,
      formValue,
      editSubmit,
      deleteSubmit,
      showEditAddModal,
      showDeleteModal,
      formSchema
    }
  }
})
</script>

<style scoped></style>
